/*
 * @Descripttion:
 * @Author: jhw
 * @Date: 2023-10-25 11:40:20
 * @LastEditors: jhw
 * @LastEditTime: 2023-12-13 14:40:35
 */
/*
 * @Descripttion: 文字移动指令
 * @Author: jhw
 * @Date: 2023-07-21 15:59:54
 * @LastEditors: jhw
 * @LastEditTime: 2023-07-24 17:09:11
 */

import { Directive, DirectiveBinding } from 'vue';

let timer: any = null;
let oldText: string = ''; // 原始文字
let oldTextWidth: number = 0; // 原始文字的宽度
// let spaceWidth: number = 42; // 空格的宽度
let parentWidth: number = 0; // 父元素的宽度

interface IConfig {
  direction?: 'left' | 'right';
  nearby?: 'always' | number | 'once';
  speed?: number;
}

// let config: IConfig = {
//   direction: 'left',
//   nearby: 'always',
// };

// 519  1038 1080   ---\u00A0 - 42
export default <Directive>{
  mounted(el: HTMLElement, binding: DirectiveBinding, vnode: any) {
    el.addEventListener('mouseenter', () => {
      let dom = el;
      let config: IConfig = Object.assign({}, { nearby: 'once', speed: 1 }, { ...binding.value });
      oldText = vnode.el.innerText;
      oldTextWidth = dom.scrollWidth;
      dom.innerText = oldText + '\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0\u00A0' + oldText;
      parentWidth = dom.offsetWidth;
      let textWidth = dom.scrollWidth;
      _run({ start: 0, end: textWidth - oldTextWidth, dom, config });
    });
    el.addEventListener('mouseleave', () => {
      timer && clearInterval(timer);
      el.innerText = oldText;
      el.style.transform = `translateX(0)`;
    });
  },
};

/**
 * @start 开始位置
 * @end 结束路程
 * @speed 速度
 * @dom dom元素
 * @endWidth 结束位置的宽度
 * @text 结束之后的文字
 */
function _run({
  start = 0,
  end,
  dom,
  config,
}: {
  start: number;
  end: number;
  speed?: number;
  dom: HTMLElement;
  config?: IConfig;
}) {
  let i = 0;
  timer = setInterval(() => {
    start += config?.speed || 1;
    // 一直循环
    if (config?.nearby === 'always') {
      if (start === end) {
        start = 0;
      }
    } else if (config?.nearby === 'once') {
      if (start === end) {
        start = 0;
        dom.innerText = oldText;
        clearInterval(timer);
        timer = null;
      }
    } else {
      if (start === end) {
        start = 0;
        console.log('i', i);
        if (i === config?.nearby) {
          dom.innerText = oldText;
          clearInterval(timer);
          timer = null;
        }
        i++;
      }
    }
    dom.style.transform = `translateX(-${start}px)`;
  }, 10);
}
